package juc.thread.threadPool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/*
 * 线程池工具类（Executors）-newSingleThreadExecutor
 * */
class Test4{
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ThreadPoolExecutor executor=(ThreadPoolExecutor) executorService;
        executor.setCorePoolSize(3);
    }
}
/*
 * 线程池工具类（Executors）-newCachedThreadPool
 * 内部使用了SynchronousQueue<Runnable>()队列 特点：当有线程take任务时主线程才能将任务放入队列
 * */
class Test3{
    public static void main(String[] args) throws InterruptedException {
        SynchronousQueue<String> synchronousQueue = new SynchronousQueue<>();
        new Thread(()->{
            try {
                String s="hello";
                System.out.println(s+"putting");
                synchronousQueue.put(s);
                System.out.println(s+"putted");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                String s="world";
                System.out.println(s+"putting");
                synchronousQueue.put(s);
                System.out.println(s+"putted");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        Thread.sleep(3000);
        System.out.println("poll");
        System.out.println(synchronousQueue.poll()+"polled");
    }
}


/*
* 线程池工具类（Executors）-newFixedThreadPool
* */
public class Test2 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2, new ThreadFactory() {
            private AtomicInteger t=new AtomicInteger(1);
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"myThreadPool-t-"+t.getAndIncrement());
            }
        });
//        ThreadPoolExecutor t=(ThreadPoolExecutor)executorService;
//        t.setCorePoolSize(3);
        executorService.submit(()->{
            System.out.println(Thread.currentThread().getName()+" 1");
        });
        executorService.submit(()->{
            System.out.println(Thread.currentThread().getName()+" 2");
        });
        executorService.submit(()->{
            System.out.println(Thread.currentThread().getName()+" 3");
        });
    }
}
